package controllers

import (
	"errors"
	"news/common/response"
	"news/constStatus"
	"news/logic"
	"news/models"

	"github.com/go-playground/validator/v10"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

func SignUpHandler(c *gin.Context) {
	p := new(models.ParamsSignUp)
	if err := c.ShouldBindJSON(p); err != nil {
		zap.L().Error("Sign with invalid param", zap.Error(err))
		errors, ok := err.(validator.ValidationErrors)
		if !ok {
			response.FailWithMessage(err.Error(), c)
			return
		}
		response.FailWithMessage(removeTopStruct(errors.Translate(trans)), c)
		return
	}
	// 返回参数信息
	if err := logic.SignUp(p); err != nil {
		zap.L().Error("logic.SignUp failed", zap.Error(err))
		if errors.Is(err, constStatus.ErrorUserExist) {
			response.FailWithMessage("用户已经存在", c)
			return
		}
		if errors.Is(err, constStatus.ErrorNOTTable) {
			response.FailWithMessage("该表不存在", c)
			return
		}
	}
	response.OkWithMessage("注册成功", nil, c)

}

// 用户登录模块

func LoginHandler(c *gin.Context) {
	p := new(models.ParamsLogin)
	if err := c.ShouldBindJSON(p); err != nil {
		zap.L().Error("login with invalid param", zap.Error(err))
		errors, ok := err.(validator.ValidationErrors)
		if !ok {
			response.FailWithMessage(err.Error(), c)
			return
		}
		response.FailWithMessage(removeTopStruct(errors.Translate(trans)), c)
		return
	}
	token, err := logic.Login(p)
	if err != nil {
		zap.L().Error("logic.Login failed", zap.String("username", p.Username), zap.Error(err))

		if errors.Is(err, constStatus.ErrorUserNotExist) {
			response.FailWithMessage(constStatus.CodeUserNotExit, c)
			return
		}
		if errors.Is(err, constStatus.ErrorInvalidPassword) {
			response.FailWithMessage(constStatus.CodeUserPassword, c)
			return
		}
		response.FailWithMessage(constStatus.CodeUserPassword, c)
		return
	}
	response.OkWithMessage("Success", token, c)
}
